package controllers

import (
	"TTSX_beego/models"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/gomodule/redigo/redis"
	"strconv"
)

type CartController struct {
	beego.Controller
}

func (This *CartController) HandleAddCart() {
	count, err1 := This.GetInt("count")
	skuId, err2 := This.GetInt("skuId")
	if err1 != nil || err2 != nil {
		jsonData := make(map[string]interface{})
		jsonData["code"] = 403
		jsonData["msg"] = "参数不正确"

		This.Data["json"] = jsonData
		This.ServeJSON()
		return
	}

	userName := This.GetSession("userName")
	if userName == nil {
		jsonData := make(map[string]interface{})
		jsonData["code"] = 403
		jsonData["msg"] = "没有登入"

		This.Data["json"] = jsonData
		This.ServeJSON()
		return
	}

	o := orm.NewOrm()
	var user models.User
	user.Name = userName.(string)
	o.Read(&user)

	conn, err := redis.Dial("tcp", "192.168.88.137:6379")
	if err != nil {
		jsonData := make(map[string]interface{})
		jsonData["code"] = 500
		jsonData["msg"] = "服务器错误"

		This.Data["json"] = jsonData
		This.ServeJSON()
		return

	}
	_, err = conn.Do("hset", "cart_"+strconv.Itoa(user.Id), skuId, count)
	if err != nil {
		jsonData := make(map[string]interface{})
		jsonData["code"] = 500
		jsonData["msg"] = "保存失败"

		This.Data["json"] = jsonData
		This.ServeJSON()
		return
	}

	CartCount, _ := redis.Int(conn.Do("hlen", "cart_"+strconv.Itoa(user.Id)))

	jsonData := make(map[string]interface{})
	jsonData["code"] = 200
	jsonData["msg"] = "ok"
	jsonData["CartCount"] = CartCount

	This.Data["json"] = jsonData
	This.ServeJSON()

}
